using UnityEngine;
using System.Collections;

public class SceneDoor : MonoBehaviour {	
	public GameObject mainRole;
	public string nextScene;
	
	Transform mainRoleTrans;
	Transform trans;
	//暂用//
	bool hasSend = false;
	
	void Awake(){
		MySocket.getInstance ().addEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_SWITCH_SCENE_ACK, SwitchScene);
	}

	// Use this for initialization
	void Start () {
		if(!mainRole) mainRole = PlayerData.Instance().MainRoleInstance;
		
		mainRoleTrans = mainRole.transform;
		trans = transform;
	}
	
	// Update is called once per frame
	void Update () 
    {	
		
		if(hasSend == true)
			return;
		
        if (Vector2Distance(mainRoleTrans.position, trans.position) <= 0.2f)
        {
            ByteArrayEx byteArray = new ByteArrayEx();
			
			int nextSceneId = PlayerData.Instance().NextScene;
			byteArray.writeInt((int)SystemMsgFlag.NetMessageCS.NM_CS_SWITCH_SCENE_SYN);
			byteArray.writeInt(nextSceneId);
			
			MySocket.getInstance ().Async_Send (byteArray.byteArray);
			
			hasSend = true;
		}
	}
	
	//切换场景返回//
	void SwitchScene (System.Object getter, DispatchEventArgs e)
	{
		ByteArrayEx byteArray = new ByteArrayEx (e.data [0] as byte[]);
		
		//解读服务器发来的数据包//
		byte result = byteArray.readByte ();
		
		if (result == (byte)CustomToClientFlag.RequestResult.success) {
			SceneManagement.GetInstance().SwitchScene("Main",true);
			
			PlayerData.Instance().SceneId = PlayerData.Instance().NextScene;
			
			hasSend = false;
		}
	}
	
	void OnDestroy(){
		MySocket.getInstance ().removeEventListener ((int)SystemMsgFlag.NetMessageSC.NM_SC_SWITCH_SCENE_ACK);
	}
	
	float Vector2Distance(Vector3 startPoint,Vector3 endPoint){
		Vector2 position1 = new Vector2(startPoint.x,startPoint.y);
		Vector2 position2 = new Vector2(endPoint.x,endPoint.y);
		
		return Vector2.Distance(position1,position2);
	}
}
